
#encoding: utf8
######################################################
#virtualenv relocate script
# Author: Curu Wong
# Date:   2014-09-17
# License: GPL v3
#######################################################
import platform
import re
import os
import sys
import glob

mydir = os.path.dirname(__file__)
new_env = os.path.dirname(mydir)

if platform.system().startswith('Windows'):
	activate_file='activate.bat'
	env_re = r'"VIRTUAL_ENV=(.+)"'
else:
	activate_file='activate'
	env_re = r"VIRTUAL_ENV=.*echo '(.+?)'"
activate_file = os.path.join(mydir, activate_file)

#get old VIRTUAL_ENV path
old_env=""
with open(activate_file) as fp:
	for line in fp:
		m = re.search(env_re, line)
		if m:
			old_env = m.group(1)
			break
print "OLD VIRTUAL_ENV=%s" % old_env
if old_env == new_env:
	print "no need to relocate"
	sys.exit(0)
print "RELOCATING TO %s" % new_env

#changing env
for bin in glob.glob(os.path.join(mydir, '*')):
	if bin.endswith(os.path.basename(__file__)):
		#skip myself
		continue
	#read original content
	with open(bin, 'rb') as bin_fp:
		bin_content = bin_fp.read()
	#replace
	bin_content_new = bin_content.replace(old_env, new_env)
	with open(bin, 'wb') as bin_fp:
		bin_fp.write(bin_content_new)
	

